import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Tree } from 'antd'
import { HTTP } from '../../utils'

const TreeNode = Tree.TreeNode

export default class extends Component {
    static propTypes = {
        url: PropTypes.string,
        params: PropTypes.object,
        defaultCheckedKeys: PropTypes.array,
        checkValue: PropTypes.func.isRequired
    }

    constructor(props) {
        super(props)
        this.state = {
            innerData: [],
            checkedValues: []
        }
    }

    componentDidMount() {
        const { url, params } = this.props
        HTTP.post(url, params, () => {}, (resp) => {
            this.setState({
                innerData: resp || []
            })
        })
    }

    geneTreeNode = (data = []) => {
        if(data.length > 0) {
            return data.map((v, i) => {
                return (
                    <TreeNode title={v.name} key={v.id}>
                        {
                            this.geneTreeNode(v.children || [])
                        }
                    </TreeNode>
                )
            })
        }
    }

    onCheck = (checkedVls) => {
        this.props.checkValue(checkedVls)
    }

    render = () => {
        if(this.state.innerData.length <= 0) {
            return (<div>loading...</div>)
        } else {
            return (
                <Tree
                    checkable
                    defaultCheckedKeys={ this.props.defaultCheckedKeys }
                    onCheck={this.onCheck}
                >
                    {
                        this.geneTreeNode(this.state.innerData)
                    }
                </Tree>
            )
        }
    }
}
